import { login, phonelogin, logout, getInfo} from '@/api/login'
import { fetchPackageApi} from '@/api/table'
import { getToken, setToken, removeToken} from '@/utils/auth'
// import { Base64} from 'js-base64'
import { getRouterSort } from '@/api/login'
import routerList from '@/router/sort-router'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    packages: {},
    routerSort: [],  // 经过排序的路由列表
    lineConfig: sessionStorage.getItem('lineConfig') && JSON.parse(sessionStorage.getItem('lineConfig') || {}) || {},
    userModuleList: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PACKAGE: (state, packages) => {
      state.packages = packages
    },
    SET_COLOR: (state, colors) => {
      if(!colors) return
      const COLORLIST = colors.line_colors.map(item => item.color)
      sessionStorage.setItem('lineConfig', JSON.stringify({
        COLORLIST,
        line_width: colors.line_width,
        fitt_line_width: colors.fitt_line_width,
      }))
    },

    // 将路由列表和路由顺序就行排序
    setRouterSort(state, payload) {
      payload.forEach(v => {
        routerList.forEach(item => {
          if(v === item.sort) {
            state.routerSort.push(item)
          }
        })
      });
    },
    SET_USER_MODULE(state, payload) {
      state.userModuleList = payload
    }
  },

  actions: {
    // 登录
    Login(context, userInfo) {
      const userName = userInfo.userName.trim()
      return new Promise((resolve, reject) => {
        login(userName, userInfo.password).then( response => {
          const data = response.data
          let baseToken = "";
          baseToken = data
          setToken(baseToken)
          context.commit('SET_TOKEN', baseToken)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户路由信息
    getRouterSort(context) {
      return new Promise((resolve, reject) => {
        getRouterSort().then(res => {
          resolve(res)
          context.commit('SET_USER_MODULE', res.data)
        }).catch(() => {
          reject()
        })
      })
    },

    // 登录
    phoneLogin({
      commit
    }, userInfo) {

      const userName = userInfo.userName.trim()

      return new Promise((resolve, reject) => {
        phonelogin(userName, userInfo.code).then(response => {
          const data = response.data
          let baseToken = "";
          baseToken = data
          setToken(baseToken)
          commit('SET_TOKEN', baseToken)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response.data
          commit('SET_ROLES', ['admin'])
          // if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组['admin','edtor']
          // commit('SET_ROLES', data.roles)
          // } else {
          //   reject('getInfo: roles must be a non-null array !')
          // }
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    //获取安装包
    GetPackage({ commit }, formData) {
      return new Promise(() => {
        fetchPackageApi(formData).then(response => {
          const data = response.data
          // console.log(data.soft, '信息');
          const packageList = {}
          packageList.install = {}
          packageList.soft = data.soft
          // packageList.install = [ ...data.fullInstall, ...data.updateInstall]
          // packageList.excel = [ ...data.operation, ...data.excel]
          packageList.document = data.document

          packageList.logic = data.logic

          commit('SET_PACKAGE', packageList)
          commit('SET_COLOR', data.color)
        })
      })
    },

    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user